package com.huahai.security.core.util;

import com.huahai.security.core.properties.SecurityProperties;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;

/**
 * @Author: Jun
 * @Date: 2020/7/17
 *
 * JWT Token生成器
 */
@Component
public class JwtTokenUtils {

    @Autowired
    private SecurityProperties securityProperties;

    public String createToken(String username, HashMap<String,Object> map){
        SecretKey secretKey = Keys.hmacShaKeyFor(securityProperties.getJwt().getJwtSecret().getBytes());

        String token = Jwts.builder()
                .setHeaderParam("TYP", securityProperties.getJwt().getJwtTokenType())
                .setClaims(map)
                .setIssuer(securityProperties.getJwt().getJwtTokenIssuer())
                .setIssuedAt(new Date())
                .setAudience(securityProperties.getJwt().getJwtTokenAudience())
                .setExpiration(new Date(System.currentTimeMillis() + securityProperties.getJwt().getJwtTokenExpireIn()))
                .setSubject(username)

                .signWith(secretKey).compact();
        token = securityProperties.getJwt().getJwtTokenPrefix() + token;

        return token;
    }
}
